using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 基于JSON文件的数据存储服务
    /// </summary>
    public class JsonDataStorageService : IDataStorageService
    {
        private readonly ILogger<JsonDataStorageService> _logger;
        private readonly string _dataDirectory;
        private readonly string _projectsFile;
        private readonly string _documentsFile;
        private readonly string _novelProjectsFile;
        private readonly string _chaptersFile;
        private readonly string _charactersFile;
        private readonly string _vectorRecordsFile;
        private readonly string _aiModelConfigsFile;
        private readonly string _worldSettingsFile;
        private readonly string _promptConfigsFile;
        private readonly string _writingWorkflowConfigsFile;

        // 内存中的数据
        private List<Project> _projects = new();
        private List<Document> _documents = new();
        private List<NovelProject> _novelProjects = new();
        private List<Chapter> _chapters = new();
        private List<Character> _characters = new();
        private List<VectorRecord> _vectorRecords = new();
        private List<AIModelConfig> _aiModelConfigs = new();
        private List<WorldSetting> _worldSettings = new();
        private List<PromptConfig> _promptConfigs = new();
        private List<WritingWorkflowConfig> _writingWorkflowConfigs = new();

        private int _nextProjectId = 1;
        private int _nextDocumentId = 1;
        private int _nextNovelProjectId = 1;
        private int _nextChapterId = 1;
        private int _nextCharacterId = 1;
        private int _nextVectorRecordId = 1;
        private int _nextAIModelConfigId = 1;
        private int _nextWorldSettingId = 1;
        private int _nextPromptConfigId = 1;
        private int _nextWritingWorkflowConfigId = 1;

        public JsonDataStorageService(ILogger<JsonDataStorageService> logger)
        {
            _logger = logger;
            _dataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DocumentCreationSystem");
            
            // 确保数据目录存在
            Directory.CreateDirectory(_dataDirectory);

            _projectsFile = Path.Combine(_dataDirectory, "projects.json");
            _documentsFile = Path.Combine(_dataDirectory, "documents.json");
            _novelProjectsFile = Path.Combine(_dataDirectory, "novel_projects.json");
            _chaptersFile = Path.Combine(_dataDirectory, "chapters.json");
            _charactersFile = Path.Combine(_dataDirectory, "characters.json");
            _vectorRecordsFile = Path.Combine(_dataDirectory, "vector_records.json");
            _aiModelConfigsFile = Path.Combine(_dataDirectory, "ai_model_configs.json");
            _worldSettingsFile = Path.Combine(_dataDirectory, "world_settings.json");
            _promptConfigsFile = Path.Combine(_dataDirectory, "prompt_configs.json");
            _writingWorkflowConfigsFile = Path.Combine(_dataDirectory, "writing_workflow_configs.json");
        }

        #region 项目管理

        public async Task<List<Project>> GetProjectsAsync()
        {
            return await Task.FromResult(_projects.ToList());
        }

        public async Task<Project?> GetProjectAsync(int id)
        {
            return await Task.FromResult(_projects.FirstOrDefault(p => p.Id == id));
        }

        public async Task<Project> CreateProjectAsync(Project project)
        {
            project.Id = _nextProjectId++;
            project.CreatedAt = DateTime.Now;
            project.UpdatedAt = DateTime.Now;
            _projects.Add(project);
            await SaveAsync();
            return project;
        }

        public async Task<Project> UpdateProjectAsync(Project project)
        {
            var existing = _projects.FirstOrDefault(p => p.Id == project.Id);
            if (existing != null)
            {
                var index = _projects.IndexOf(existing);
                project.UpdatedAt = DateTime.Now;
                _projects[index] = project;
                await SaveAsync();
            }
            return project;
        }

        public async Task DeleteProjectAsync(int id)
        {
            _projects.RemoveAll(p => p.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 文档管理

        public async Task<List<Document>> GetDocumentsAsync(int projectId)
        {
            return await Task.FromResult(_documents.Where(d => d.ProjectId == projectId).ToList());
        }

        public async Task<Document?> GetDocumentAsync(int id)
        {
            return await Task.FromResult(_documents.FirstOrDefault(d => d.Id == id));
        }

        public async Task<Document> CreateDocumentAsync(Document document)
        {
            document.Id = _nextDocumentId++;
            document.CreatedAt = DateTime.Now;
            document.UpdatedAt = DateTime.Now;
            _documents.Add(document);
            await SaveAsync();
            return document;
        }

        public async Task<Document> UpdateDocumentAsync(Document document)
        {
            var existing = _documents.FirstOrDefault(d => d.Id == document.Id);
            if (existing != null)
            {
                var index = _documents.IndexOf(existing);
                document.UpdatedAt = DateTime.Now;
                _documents[index] = document;
                await SaveAsync();
            }
            return document;
        }

        public async Task DeleteDocumentAsync(int id)
        {
            _documents.RemoveAll(d => d.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 小说项目管理

        public async Task<NovelProject?> GetNovelProjectAsync(int novelProjectId)
        {
            return await Task.FromResult(_novelProjects.FirstOrDefault(np => np.Id == novelProjectId));
        }

        public async Task<NovelProject?> GetNovelProjectByProjectIdAsync(int projectId)
        {
            return await Task.FromResult(_novelProjects.FirstOrDefault(np => np.ProjectId == projectId));
        }

        public async Task<NovelProject> CreateNovelProjectAsync(NovelProject novelProject)
        {
            novelProject.Id = _nextNovelProjectId++;
            novelProject.CreatedAt = DateTime.Now;
            novelProject.UpdatedAt = DateTime.Now;
            _novelProjects.Add(novelProject);
            await SaveAsync();
            return novelProject;
        }

        public async Task<NovelProject> UpdateNovelProjectAsync(NovelProject novelProject)
        {
            var existing = _novelProjects.FirstOrDefault(np => np.Id == novelProject.Id);
            if (existing != null)
            {
                var index = _novelProjects.IndexOf(existing);
                novelProject.UpdatedAt = DateTime.Now;
                _novelProjects[index] = novelProject;
                await SaveAsync();
            }
            return novelProject;
        }

        #endregion

        #region 章节管理

        public async Task<List<Chapter>> GetChaptersAsync(int novelProjectId)
        {
            return await Task.FromResult(_chapters.Where(c => c.NovelProjectId == novelProjectId).ToList());
        }

        public async Task<Chapter?> GetChapterAsync(int id)
        {
            return await Task.FromResult(_chapters.FirstOrDefault(c => c.Id == id));
        }

        public async Task<Chapter> CreateChapterAsync(Chapter chapter)
        {
            chapter.Id = _nextChapterId++;
            chapter.CreatedAt = DateTime.Now;
            chapter.UpdatedAt = DateTime.Now;
            _chapters.Add(chapter);
            await SaveAsync();
            return chapter;
        }

        public async Task<Chapter> UpdateChapterAsync(Chapter chapter)
        {
            var existing = _chapters.FirstOrDefault(c => c.Id == chapter.Id);
            if (existing != null)
            {
                var index = _chapters.IndexOf(existing);
                chapter.UpdatedAt = DateTime.Now;
                _chapters[index] = chapter;
                await SaveAsync();
            }
            return chapter;
        }

        public async Task DeleteChapterAsync(int id)
        {
            _chapters.RemoveAll(c => c.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 角色管理

        public async Task<List<Character>> GetCharactersAsync(int novelProjectId)
        {
            return await Task.FromResult(_characters.Where(c => c.NovelProjectId == novelProjectId).ToList());
        }

        public async Task<Character?> GetCharacterAsync(int id)
        {
            return await Task.FromResult(_characters.FirstOrDefault(c => c.Id == id));
        }

        public async Task<Character> CreateCharacterAsync(Character character)
        {
            character.Id = _nextCharacterId++;
            character.CreatedAt = DateTime.Now;
            character.UpdatedAt = DateTime.Now;
            _characters.Add(character);
            await SaveAsync();
            return character;
        }

        public async Task<Character> UpdateCharacterAsync(Character character)
        {
            var existing = _characters.FirstOrDefault(c => c.Id == character.Id);
            if (existing != null)
            {
                var index = _characters.IndexOf(existing);
                character.UpdatedAt = DateTime.Now;
                _characters[index] = character;
                await SaveAsync();
            }
            return character;
        }

        public async Task DeleteCharacterAsync(int id)
        {
            _characters.RemoveAll(c => c.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 向量记录管理

        public async Task<List<VectorRecord>> GetVectorRecordsAsync(int documentId)
        {
            return await Task.FromResult(_vectorRecords.Where(vr => vr.DocumentId == documentId).ToList());
        }

        public async Task<VectorRecord?> GetVectorRecordAsync(int id)
        {
            return await Task.FromResult(_vectorRecords.FirstOrDefault(vr => vr.Id == id));
        }

        public async Task<VectorRecord> CreateVectorRecordAsync(VectorRecord vectorRecord)
        {
            vectorRecord.Id = _nextVectorRecordId++;
            vectorRecord.CreatedAt = DateTime.Now;
            vectorRecord.UpdatedAt = DateTime.Now;
            _vectorRecords.Add(vectorRecord);
            await SaveAsync();
            return vectorRecord;
        }

        public async Task<VectorRecord> UpdateVectorRecordAsync(VectorRecord vectorRecord)
        {
            var existing = _vectorRecords.FirstOrDefault(vr => vr.Id == vectorRecord.Id);
            if (existing != null)
            {
                var index = _vectorRecords.IndexOf(existing);
                vectorRecord.UpdatedAt = DateTime.Now;
                _vectorRecords[index] = vectorRecord;
                await SaveAsync();
            }
            return vectorRecord;
        }

        public async Task DeleteVectorRecordAsync(int id)
        {
            _vectorRecords.RemoveAll(vr => vr.Id == id);
            await SaveAsync();
        }

        #endregion

        #region AI模型配置管理

        public async Task<List<AIModelConfig>> GetAIModelConfigsAsync()
        {
            return await Task.FromResult(_aiModelConfigs.ToList());
        }

        public async Task<AIModelConfig?> GetAIModelConfigAsync(int id)
        {
            return await Task.FromResult(_aiModelConfigs.FirstOrDefault(c => c.Id == id));
        }

        public async Task<AIModelConfig> CreateAIModelConfigAsync(AIModelConfig config)
        {
            config.Id = _nextAIModelConfigId++;
            config.CreatedAt = DateTime.Now;
            config.UpdatedAt = DateTime.Now;
            _aiModelConfigs.Add(config);
            await SaveAsync();
            return config;
        }

        public async Task<AIModelConfig> UpdateAIModelConfigAsync(AIModelConfig config)
        {
            var existing = _aiModelConfigs.FirstOrDefault(c => c.Id == config.Id);
            if (existing != null)
            {
                var index = _aiModelConfigs.IndexOf(existing);
                config.UpdatedAt = DateTime.Now;
                _aiModelConfigs[index] = config;
                await SaveAsync();
            }
            return config;
        }

        public async Task DeleteAIModelConfigAsync(int id)
        {
            _aiModelConfigs.RemoveAll(c => c.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 世界设定管理

        public async Task<WorldSetting?> GetWorldSettingAsync(int novelProjectId)
        {
            return await Task.FromResult(_worldSettings.FirstOrDefault(ws => ws.NovelProjectId == novelProjectId));
        }

        public async Task<WorldSetting> CreateWorldSettingAsync(WorldSetting worldSetting)
        {
            worldSetting.Id = _nextWorldSettingId++;
            worldSetting.CreatedAt = DateTime.Now;
            worldSetting.UpdatedAt = DateTime.Now;
            _worldSettings.Add(worldSetting);
            await SaveAsync();
            return worldSetting;
        }

        public async Task<WorldSetting> UpdateWorldSettingAsync(WorldSetting worldSetting)
        {
            var index = _worldSettings.FindIndex(ws => ws.Id == worldSetting.Id);
            if (index >= 0)
            {
                worldSetting.UpdatedAt = DateTime.Now;
                _worldSettings[index] = worldSetting;
                await SaveAsync();
            }
            return worldSetting;
        }

        public async Task DeleteWorldSettingAsync(int id)
        {
            _worldSettings.RemoveAll(ws => ws.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 数据持久化

        public async Task SaveAsync()
        {
            try
            {
                await SaveToFileAsync(_projectsFile, _projects);
                await SaveToFileAsync(_documentsFile, _documents);
                await SaveToFileAsync(_novelProjectsFile, _novelProjects);
                await SaveToFileAsync(_chaptersFile, _chapters);
                await SaveToFileAsync(_charactersFile, _characters);
                await SaveToFileAsync(_vectorRecordsFile, _vectorRecords);
                await SaveToFileAsync(_aiModelConfigsFile, _aiModelConfigs);
                await SaveToFileAsync(_worldSettingsFile, _worldSettings);
                await SaveToFileAsync(_promptConfigsFile, _promptConfigs);
                await SaveToFileAsync(_writingWorkflowConfigsFile, _writingWorkflowConfigs);

                _logger.LogInformation("数据保存成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存数据时发生错误");
                throw;
            }
        }

        public async Task LoadAsync()
        {
            try
            {
                // 确保数据目录存在
                if (!Directory.Exists(_dataDirectory))
                {
                    Directory.CreateDirectory(_dataDirectory);
                    _logger.LogInformation($"创建数据目录: {_dataDirectory}");
                }

                _projects = await LoadFromFileAsync<Project>(_projectsFile) ?? new List<Project>();
                _documents = await LoadFromFileAsync<Document>(_documentsFile) ?? new List<Document>();
                _novelProjects = await LoadFromFileAsync<NovelProject>(_novelProjectsFile) ?? new List<NovelProject>();
                _chapters = await LoadFromFileAsync<Chapter>(_chaptersFile) ?? new List<Chapter>();
                _characters = await LoadFromFileAsync<Character>(_charactersFile) ?? new List<Character>();
                _vectorRecords = await LoadFromFileAsync<VectorRecord>(_vectorRecordsFile) ?? new List<VectorRecord>();
                _aiModelConfigs = await LoadFromFileAsync<AIModelConfig>(_aiModelConfigsFile) ?? new List<AIModelConfig>();
                _promptConfigs = await LoadFromFileAsync<PromptConfig>(_promptConfigsFile) ?? new List<PromptConfig>();
                _writingWorkflowConfigs = await LoadFromFileAsync<WritingWorkflowConfig>(_writingWorkflowConfigsFile) ?? new List<WritingWorkflowConfig>();
                _worldSettings = await LoadFromFileAsync<WorldSetting>(_worldSettingsFile) ?? new List<WorldSetting>();

                // 更新ID计数器
                _nextProjectId = _projects.Any() ? _projects.Max(p => p.Id) + 1 : 1;
                _nextDocumentId = _documents.Any() ? _documents.Max(d => d.Id) + 1 : 1;
                _nextNovelProjectId = _novelProjects.Any() ? _novelProjects.Max(np => np.Id) + 1 : 1;
                _nextChapterId = _chapters.Any() ? _chapters.Max(c => c.Id) + 1 : 1;
                _nextCharacterId = _characters.Any() ? _characters.Max(c => c.Id) + 1 : 1;
                _nextVectorRecordId = _vectorRecords.Any() ? _vectorRecords.Max(vr => vr.Id) + 1 : 1;
                _nextAIModelConfigId = _aiModelConfigs.Any() ? _aiModelConfigs.Max(c => c.Id) + 1 : 1;
                _nextWorldSettingId = _worldSettings.Any() ? _worldSettings.Max(ws => ws.Id) + 1 : 1;
                _nextPromptConfigId = _promptConfigs.Any() ? _promptConfigs.Max(c => c.Id) + 1 : 1;
                _nextWritingWorkflowConfigId = _writingWorkflowConfigs.Any() ? _writingWorkflowConfigs.Max(c => c.Id) + 1 : 1;

                _logger.LogInformation($"数据加载成功 - 项目: {_projects.Count}, 小说项目: {_novelProjects.Count}, 章节: {_chapters.Count}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载数据时发生错误");
                // 如果加载失败，使用空数据
                _projects = new List<Project>();
                _documents = new List<Document>();
                _novelProjects = new List<NovelProject>();
                _chapters = new List<Chapter>();
                _characters = new List<Character>();
                _vectorRecords = new List<VectorRecord>();
                _aiModelConfigs = new List<AIModelConfig>();
                _worldSettings = new List<WorldSetting>();
                _promptConfigs = new List<PromptConfig>();
                _writingWorkflowConfigs = new List<WritingWorkflowConfig>();

                // 重置ID计数器
                _nextProjectId = 1;
                _nextDocumentId = 1;
                _nextNovelProjectId = 1;
                _nextChapterId = 1;
                _nextCharacterId = 1;
                _nextVectorRecordId = 1;
                _nextAIModelConfigId = 1;
                _nextPromptConfigId = 1;
                _nextWritingWorkflowConfigId = 1;
            }
        }

        private async Task SaveToFileAsync<T>(string filePath, List<T> data)
        {
            var json = JsonConvert.SerializeObject(data, Formatting.Indented);
            await File.WriteAllTextAsync(filePath, json);
        }

        private async Task<List<T>?> LoadFromFileAsync<T>(string filePath)
        {
            if (!File.Exists(filePath))
                return null;

            var json = await File.ReadAllTextAsync(filePath);
            return JsonConvert.DeserializeObject<List<T>>(json);
        }

        #endregion

        #region 数据清理和验证

        /// <summary>
        /// 清理无效的项目ID引用
        /// </summary>
        public async Task<DataCleanupResult> CleanupInvalidProjectReferencesAsync()
        {
            var result = new DataCleanupResult();

            try
            {
                _logger.LogInformation("开始清理无效的项目ID引用...");

                // 获取所有有效的项目ID
                var validProjectIds = _projects.Where(p => p.Status != "Deleted").Select(p => p.Id).ToHashSet();
                _logger.LogInformation($"有效项目ID数量: {validProjectIds.Count}");

                // 清理文档中的无效项目引用
                var invalidDocuments = _documents.Where(d => !validProjectIds.Contains(d.ProjectId)).ToList();
                if (invalidDocuments.Any())
                {
                    _logger.LogWarning($"发现 {invalidDocuments.Count} 个引用无效项目ID的文档");
                    foreach (var doc in invalidDocuments)
                    {
                        _logger.LogWarning($"  文档ID: {doc.Id}, 引用的无效项目ID: {doc.ProjectId}");
                        result.InvalidDocuments.Add(doc);
                    }

                    // 移除无效文档
                    _documents.RemoveAll(d => !validProjectIds.Contains(d.ProjectId));
                    result.RemovedDocumentsCount = invalidDocuments.Count;
                }

                // 清理小说项目中的无效项目引用
                var invalidNovelProjects = _novelProjects.Where(np => !validProjectIds.Contains(np.ProjectId)).ToList();
                if (invalidNovelProjects.Any())
                {
                    _logger.LogWarning($"发现 {invalidNovelProjects.Count} 个引用无效项目ID的小说项目");
                    foreach (var np in invalidNovelProjects)
                    {
                        _logger.LogWarning($"  小说项目ID: {np.Id}, 引用的无效项目ID: {np.ProjectId}");
                        result.InvalidNovelProjects.Add(np);
                    }

                    // 移除无效小说项目
                    _novelProjects.RemoveAll(np => !validProjectIds.Contains(np.ProjectId));
                    result.RemovedNovelProjectsCount = invalidNovelProjects.Count;
                }

                // 获取所有有效的小说项目ID
                var validNovelProjectIds = _novelProjects.Select(np => np.Id).ToHashSet();

                // 清理章节中的无效小说项目引用
                var invalidChapters = _chapters.Where(c => !validNovelProjectIds.Contains(c.NovelProjectId)).ToList();
                if (invalidChapters.Any())
                {
                    _logger.LogWarning($"发现 {invalidChapters.Count} 个引用无效小说项目ID的章节");
                    foreach (var chapter in invalidChapters)
                    {
                        _logger.LogWarning($"  章节ID: {chapter.Id}, 引用的无效小说项目ID: {chapter.NovelProjectId}");
                        result.InvalidChapters.Add(chapter);
                    }

                    // 移除无效章节
                    _chapters.RemoveAll(c => !validNovelProjectIds.Contains(c.NovelProjectId));
                    result.RemovedChaptersCount = invalidChapters.Count;
                }

                // 清理角色中的无效小说项目引用
                var invalidCharacters = _characters.Where(c => !validNovelProjectIds.Contains(c.NovelProjectId)).ToList();
                if (invalidCharacters.Any())
                {
                    _logger.LogWarning($"发现 {invalidCharacters.Count} 个引用无效小说项目ID的角色");
                    foreach (var character in invalidCharacters)
                    {
                        _logger.LogWarning($"  角色ID: {character.Id}, 引用的无效小说项目ID: {character.NovelProjectId}");
                        result.InvalidCharacters.Add(character);
                    }

                    // 移除无效角色
                    _characters.RemoveAll(c => !validNovelProjectIds.Contains(c.NovelProjectId));
                    result.RemovedCharactersCount = invalidCharacters.Count;
                }

                // 获取所有有效的文档ID
                var validDocumentIds = _documents.Select(d => d.Id).ToHashSet();

                // 清理向量记录中的无效文档引用
                var invalidVectorRecords = _vectorRecords.Where(vr => !validDocumentIds.Contains(vr.DocumentId)).ToList();
                if (invalidVectorRecords.Any())
                {
                    _logger.LogWarning($"发现 {invalidVectorRecords.Count} 个引用无效文档ID的向量记录");
                    foreach (var vr in invalidVectorRecords)
                    {
                        _logger.LogWarning($"  向量记录ID: {vr.Id}, 引用的无效文档ID: {vr.DocumentId}");
                        result.InvalidVectorRecords.Add(vr);
                    }

                    // 移除无效向量记录
                    _vectorRecords.RemoveAll(vr => !validDocumentIds.Contains(vr.DocumentId));
                    result.RemovedVectorRecordsCount = invalidVectorRecords.Count;
                }

                // 清理世界设定中的无效小说项目引用
                var invalidWorldSettings = _worldSettings.Where(ws => !validNovelProjectIds.Contains(ws.NovelProjectId)).ToList();
                if (invalidWorldSettings.Any())
                {
                    _logger.LogWarning($"发现 {invalidWorldSettings.Count} 个引用无效小说项目ID的世界设定");
                    foreach (var ws in invalidWorldSettings)
                    {
                        _logger.LogWarning($"  世界设定ID: {ws.Id}, 引用的无效小说项目ID: {ws.NovelProjectId}");
                        result.InvalidWorldSettings.Add(ws);
                    }

                    // 移除无效世界设定
                    _worldSettings.RemoveAll(ws => !validNovelProjectIds.Contains(ws.NovelProjectId));
                    result.RemovedWorldSettingsCount = invalidWorldSettings.Count;
                }

                // 如果有任何清理操作，保存数据
                if (result.HasAnyCleanup)
                {
                    await SaveAsync();
                    _logger.LogInformation("数据清理完成，已保存更改");
                }
                else
                {
                    _logger.LogInformation("未发现需要清理的无效引用");
                }

                result.IsSuccess = true;
                result.Message = $"清理完成 - 文档: {result.RemovedDocumentsCount}, 小说项目: {result.RemovedNovelProjectsCount}, 章节: {result.RemovedChaptersCount}, 角色: {result.RemovedCharactersCount}, 向量记录: {result.RemovedVectorRecordsCount}, 世界设定: {result.RemovedWorldSettingsCount}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理无效项目引用时发生错误");
                result.IsSuccess = false;
                result.Message = $"清理失败: {ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 验证数据完整性
        /// </summary>
        public async Task<DataIntegrityReport> ValidateDataIntegrityAsync()
        {
            var report = new DataIntegrityReport();

            try
            {
                _logger.LogInformation("开始验证数据完整性...");

                // 验证项目引用
                var validProjectIds = _projects.Where(p => p.Status != "Deleted").Select(p => p.Id).ToHashSet();

                report.OrphanedDocuments = _documents.Where(d => !validProjectIds.Contains(d.ProjectId)).ToList();
                report.OrphanedNovelProjects = _novelProjects.Where(np => !validProjectIds.Contains(np.ProjectId)).ToList();

                // 验证小说项目引用
                var validNovelProjectIds = _novelProjects.Select(np => np.Id).ToHashSet();

                report.OrphanedChapters = _chapters.Where(c => !validNovelProjectIds.Contains(c.NovelProjectId)).ToList();
                report.OrphanedCharacters = _characters.Where(c => !validNovelProjectIds.Contains(c.NovelProjectId)).ToList();
                report.OrphanedWorldSettings = _worldSettings.Where(ws => !validNovelProjectIds.Contains(ws.NovelProjectId)).ToList();

                // 验证文档引用
                var validDocumentIds = _documents.Select(d => d.Id).ToHashSet();
                report.OrphanedVectorRecords = _vectorRecords.Where(vr => !validDocumentIds.Contains(vr.DocumentId)).ToList();

                // 检查重复ID
                report.DuplicateProjectIds = _projects.GroupBy(p => p.Id).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
                report.DuplicateDocumentIds = _documents.GroupBy(d => d.Id).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
                report.DuplicateNovelProjectIds = _novelProjects.GroupBy(np => np.Id).Where(g => g.Count() > 1).Select(g => g.Key).ToList();

                report.IsValid = !report.HasAnyIssues;
                report.GeneratedAt = DateTime.Now;

                _logger.LogInformation($"数据完整性验证完成 - 发现问题: {report.TotalIssuesCount}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证数据完整性时发生错误");
                report.IsValid = false;
                report.ErrorMessage = ex.Message;
            }

            return report;
        }

        #endregion

        #region 提示词配置管理

        public async Task<List<PromptConfig>> GetPromptConfigsAsync()
        {
            return await Task.FromResult(_promptConfigs.ToList());
        }

        public async Task<PromptConfig?> GetPromptConfigAsync(int id)
        {
            return await Task.FromResult(_promptConfigs.FirstOrDefault(c => c.Id == id));
        }

        public async Task<PromptConfig> CreatePromptConfigAsync(PromptConfig config)
        {
            config.Id = _nextPromptConfigId++;
            config.CreatedAt = DateTime.Now;
            config.UpdatedAt = DateTime.Now;
            _promptConfigs.Add(config);
            await SaveAsync();
            return config;
        }

        public async Task<PromptConfig> UpdatePromptConfigAsync(PromptConfig config)
        {
            var existing = _promptConfigs.FirstOrDefault(c => c.Id == config.Id);
            if (existing != null)
            {
                var index = _promptConfigs.IndexOf(existing);
                config.UpdatedAt = DateTime.Now;
                _promptConfigs[index] = config;
                await SaveAsync();
            }
            return config;
        }

        public async Task DeletePromptConfigAsync(int id)
        {
            _promptConfigs.RemoveAll(c => c.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 写书流程配置管理

        public async Task<List<WritingWorkflowConfig>> GetWritingWorkflowConfigsAsync()
        {
            return await Task.FromResult(_writingWorkflowConfigs.ToList());
        }

        public async Task<WritingWorkflowConfig?> GetWritingWorkflowConfigAsync(int id)
        {
            return await Task.FromResult(_writingWorkflowConfigs.FirstOrDefault(c => c.Id == id));
        }

        public async Task<WritingWorkflowConfig> CreateWritingWorkflowConfigAsync(WritingWorkflowConfig config)
        {
            config.Id = _nextWritingWorkflowConfigId++;
            config.CreatedAt = DateTime.Now;
            config.UpdatedAt = DateTime.Now;
            _writingWorkflowConfigs.Add(config);
            await SaveAsync();
            return config;
        }

        public async Task<WritingWorkflowConfig> UpdateWritingWorkflowConfigAsync(WritingWorkflowConfig config)
        {
            var existing = _writingWorkflowConfigs.FirstOrDefault(c => c.Id == config.Id);
            if (existing != null)
            {
                var index = _writingWorkflowConfigs.IndexOf(existing);
                config.UpdatedAt = DateTime.Now;
                _writingWorkflowConfigs[index] = config;
                await SaveAsync();
            }
            return config;
        }

        public async Task DeleteWritingWorkflowConfigAsync(int id)
        {
            _writingWorkflowConfigs.RemoveAll(c => c.Id == id);
            await SaveAsync();
        }

        #endregion

        #region 通用键值存储

        private readonly Dictionary<string, (object Value, DateTime? Expiration)> _keyValueStore = new();

        public async Task<T?> GetAsync<T>(string key) where T : class
        {
            await Task.CompletedTask; // 保持异步接口一致性

            if (_keyValueStore.TryGetValue(key, out var entry))
            {
                // 检查是否过期
                if (entry.Expiration.HasValue && DateTime.Now > entry.Expiration.Value)
                {
                    _keyValueStore.Remove(key);
                    return null;
                }

                return entry.Value as T;
            }

            return null;
        }

        public async Task SaveAsync<T>(string key, T value) where T : class
        {
            await Task.CompletedTask; // 保持异步接口一致性
            _keyValueStore[key] = (value, null);
        }

        public async Task SaveAsync<T>(string key, T value, TimeSpan expiration) where T : class
        {
            await Task.CompletedTask; // 保持异步接口一致性
            var expirationTime = DateTime.Now.Add(expiration);
            _keyValueStore[key] = (value, expirationTime);
        }

        public async Task<bool> DeleteAsync(string key)
        {
            await Task.CompletedTask; // 保持异步接口一致性
            return _keyValueStore.Remove(key);
        }

        public async Task<bool> ExistsAsync(string key)
        {
            await Task.CompletedTask; // 保持异步接口一致性

            if (_keyValueStore.TryGetValue(key, out var entry))
            {
                // 检查是否过期
                if (entry.Expiration.HasValue && DateTime.Now > entry.Expiration.Value)
                {
                    _keyValueStore.Remove(key);
                    return false;
                }

                return true;
            }

            return false;
        }

        #endregion
    }
}
